import React from 'react';
import { Modal, Form, Input, notification } from 'antd';
import { FormComponentProps } from 'antd/es/form';
import { editStudents, studentsList, sendMessage } from '@/services/api';
import { SIZE, PAGE } from '@/utils/constant';

interface props {
  onClose: () => void;
  dispatch: any;
}

interface UserFormProps extends FormComponentProps {
  ref: any;
}

const ref: any = React.createRef();
const { Item } = Form;
const MyForm = Form.create<UserFormProps>()(({ form: { getFieldDecorator } }: any) => {
  const formItemLayout = {
    labelCol: {
      xs: { span: 4, offset: 4 },
    },
    wrapperCol: {
      sm: { span: 8 },
    },
  };

  return (
    <Form layout="horizontal" {...formItemLayout}>
      <Item label="应缴学费">
        {getFieldDecorator('money', {
          rules: [
            {
              required: true,
              message: '必填',
            },
            {
              validator(rule: any, value: any, callback: any) {
                const reg = /^\d*\.{0,1}\d{0,2}$/;
                if (!reg.test(value)) {
                  callback(new Error('金额格式错误'));
                }
                callback([]);
              },
              message: '金额格式错误',
            },
          ],
        })(<Input addonAfter="元" placeholder="请输入" />)}
      </Item>
    </Form>
  );
});

const ApplyModal = ({ onClose, dispatch }: props) => {
  const studentsData = JSON.parse(sessionStorage.getItem('studentsData') || '');
  return (
    <Modal
      visible
      onCancel={onClose}
      maskClosable={false}
      title="应缴学费"
      onOk={() => {
        ref.current.validateFields({ first: true }, (err: any, val: any) => {
          if (!err) {
            const nowDate = new Date().toLocaleString();
            const newVal: any = {
              is_paid: true,
              is_arranged: true,
            };
            const residence_images: any = [];
            const health_images: any = [];
            const numValue = Number(val.money) * 100;
            newVal.money = numValue;
            studentsData.residences.forEach((item: any) => {
              residence_images.push(item.id);
            });
            studentsData.healths.forEach((item: any) => {
              health_images.push(item.id);
            });
            newVal.residence_images = residence_images;
            newVal.health_images = health_images;
            delete studentsData.parent;
            delete studentsData.teacher;
            delete studentsData.clase;
            delete studentsData.image;
            delete studentsData.residences;
            delete studentsData.healths;

            editStudents({ ...studentsData, ...newVal }).then((resp: any) => {
              if (resp.status === 'success') {
                notification.success({ message: '应缴学费录入成功' });
                // //缴费信息录入成功后 ，发送消息
                // sendMessage({
                //   receive_type: 1,
                //   message_type_id: 3,
                //   sender_id: studentsData.teacher_id,
                //   receiver_id: studentsData.parent_id,
                //   title: '缴费信息',
                //   content: `缴费信息:您在${nowDate}缴费了人民币￥${numValue / 100}`,
                // }).then((resp: any) => {
                //   if (resp.status === 'success') {
                //     notification.success({
                //       message: '缴费信息发送成功',
                //     });
                //   }
                // });
                onClose();
                dispatch({
                  type: 'OPEN_LOADING',
                });
                studentsList({ page: PAGE, size: SIZE })
                  .then((res: any) => {
                    if (res.status === 'success') {
                      dispatch({
                        type: 'GET_DATA',
                        payload: res.data.data,
                      });
                      dispatch({
                        type: 'CHANGE_PAGINATION',
                        payload: {
                          current: PAGE,
                          pageSize: SIZE,
                          total: res.data.meta.total,
                        },
                      });
                    }
                    dispatch({
                      type: 'CLOSED_LOADING',
                    });
                  })
                  .catch(() => {
                    dispatch({
                      type: 'CLOSED_LOADING',
                    });
                  });
              }
            });
          }
        });
      }}
    >
      <MyForm ref={ref} />
    </Modal>
  );
};

export default ApplyModal;
